package com.jihu.mall.member.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.jihu.mall.member.dao.MemberLevelDao;
import com.jihu.mall.member.entity.MemberLevelEntity;
import com.jihu.mall.member.exception.PhoneExsitException;
import com.jihu.mall.member.exception.UsernameExistException;
import com.jihu.mall.member.vo.MemberRegisterVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import java.util.Map;
import java.util.Objects;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jihu.mall.common.utils.PageUtils;
import com.jihu.mall.common.utils.Query;

import com.jihu.mall.member.dao.MemberDao;
import com.jihu.mall.member.entity.MemberEntity;
import com.jihu.mall.member.service.MemberService;


@Service("memberService")
public class MemberServiceImpl extends ServiceImpl<MemberDao, MemberEntity> implements MemberService {

    @Autowired
    private MemberLevelDao memberLevelDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<MemberEntity> page = this.page(
                new Query<MemberEntity>().getPage(params),
                new QueryWrapper<MemberEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void register(MemberRegisterVo vo) {
        MemberEntity entity = new MemberEntity();

        //设置默认等级
        MemberLevelEntity memberLevel = memberLevelDao.getDefaultLevel();
        entity.setLevelId(Objects.isNull(memberLevel) ? null : memberLevel.getId());

        //检查用户名和手机号是否唯一
        checkPhoneUnique(vo.getPhone());
        checkUsernameUnique(vo.getUsername());

        entity.setMobile(vo.getPhone());
        entity.setUsername(vo.getUsername());

        //密码进行加密存储
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        entity.setPassword(passwordEncoder.encode(vo.getPassword()));

        //其它默认信息
        this.baseMapper.insert(entity);
    }

    @Override
    public void checkPhoneUnique(String phone) throws  PhoneExsitException{
        Integer count = this.baseMapper.selectCount(new LambdaQueryWrapper<MemberEntity>().eq(MemberEntity::getMobile, phone));
        if(count > 0 ){
            throw new PhoneExsitException();
        }
    }

    @Override
    public void checkUsernameUnique(String username) throws  UsernameExistException {
        Integer count = this.baseMapper.selectCount(new LambdaQueryWrapper<MemberEntity>().eq(MemberEntity::getUsername, username));
        if(count > 0 ){
            throw new UsernameExistException();
        }
    }

}